package com.microframework.base.core.util;


import java.util.ArrayList;
import java.util.List;

import com.microframework.base.core.model.options.TreeNode;

public class TreeUtil {
    
    public static <T extends TreeNode<T>> List<T> recurOptions(List<T> list, String rootId) {
        List<T> result = new ArrayList<>();
        for (T item : list) {
            if (rootId != null) {
                if (rootId.equals(item.getParentId())) {
                    result.add(buildTree(item, list));
                }
            } else {
                if ("-1".equals(item.getParentId())) {
                    result.add(buildTree(item, list));
                }
            }
        }
        return result;
    }

    private static <T extends TreeNode<T>> T buildTree(T node, List<T> list) {
        List<T> children = new ArrayList<>();
        for (T item : list) {
            if (node.getId().equals(item.getParentId())) {
                children.add(buildTree(item, list));
            }
        }
        if (!children.isEmpty()) {
            node.setChildren(children);
        }
        return node;
    }
}

